﻿using Dapper;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Formats.Asn1;
using System.Linq;
using System.Reflection.PortableExecutable;
using System.Text;
using System.Threading.Tasks;
using WitsWebApi.DataContext.DapperHelper;
using WitsWebApi.Entity.Entities;
using WitsWebApi.Entity.EntityParam;
using WitsWebApi.Entity.PageHelper;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
using Machine = WitsWebApi.Entity.Entities.Machine;

namespace WitsWebApi.DataContext.DapperRepositories
{
    public class MachineRepository : IMachineRepository
    {
        private readonly DapperContext _context;
        public MachineRepository(DapperContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 根据设备名获取指定设备
        /// </summary>
        /// <param name="MachineName"></param>
        /// <returns></returns>
        public async Task<Machine> GetMachineDetailByName(string MachineName)
        {
            var query = "select * from machine where MachineName=@MachineName";
            using (var connection = _context.CreateConnection())
            {
                var publishers = await connection.QueryAsync<Machine>(query, new { MachineName });
                var result = publishers?.FirstOrDefault();
                return result;
            }
        }

        /// <summary>
        /// 添加设备
        /// </summary>
        /// <param name="machineParam"></param>
        /// <returns></returns>
        public async Task<int> AddMachine(MachineParam machineParam)
        {
            var query = "insert into machine (machineName,machineWorker,machineWorkshop) values(@machineName,@machineWorker,@machineWorkshop)" + "SELECT CAST(SCOPE_IDENTITY() as int)";
            var parameters = new DynamicParameters();
            parameters.Add("machineName", machineParam.MachineName, DbType.String);
            parameters.Add("machineWorker", machineParam.MachineWorker, DbType.Int32);
            parameters.Add("machineWorkshop", machineParam.MachineWorkshop, DbType.Int32);

            using (var connection = _context.CreateConnection())
            {
                int id = await connection.QuerySingleAsync<int>(query, parameters);
                return id;
            }
        }

        /// <summary>
        /// 分页
        /// </summary>
        /// <param name="machinePageResult"></param>
        /// <returns></returns>
        public async Task<Paged<Machine>> GetPageList(MachinePageResult machinePageResult)
        {
            string tableName = "machine";
            string where = "1=1";
            string orderby = "machineid";
            int RowNumMin = 1, RowNumMax = 1, total = 0;

            // 计算本次要取的条
            if (machinePageResult.PageIndex > 0)
            {
                RowNumMax = machinePageResult.PageSize * machinePageResult.PageIndex;
                int strRowNumMin = machinePageResult.PageSize * (machinePageResult.PageIndex - 1) + 1;
                RowNumMin = strRowNumMin >= 1 ? strRowNumMin : 1;
            }

            // 取数据
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("SELECT COUNT(1) FROM {0} where {1};", tableName, where);
            sb.AppendFormat(@"SELECT *
                              FROM(SELECT ROW_NUMBER() OVER(ORDER BY {2}) AS RowNum,*
                              FROM  {0} WHERE {1}) AS result
                              WHERE  RowNum >= {3} AND RowNum <= {4}
                              ORDER BY {2}", tableName, where, orderby, RowNumMin, RowNumMax);
            using (var connection = _context.CreateConnection())
            {
                using (var reader = connection.QueryMultiple(sb.ToString()))
                {
                    total = await reader.ReadFirstAsync<int>();
                    var read = await reader.ReadAsync<Machine>();
                    var list = new PageDataContext<Machine>();
                    var result = list.GetPagedData(machinePageResult, total, read.Count(), read);
                    return result;
                }
            }
        }

    }
}
